"""
@Project:${2108a 人工智能}
@File:pay.py
@Author:周家昌
@Date:8:54
"""
from flask import Blueprint,g,jsonify
from flask_restful import Api,Resource,fields,reqparse
from common.utils.login_auth import login_auth
import datetime,random
from alipay import AliPay
from common.utils.custom_resp_json import custom_json
from common.models.pay import *
import logging
from django.db import transaction # 事务



pay_bp = Blueprint('pay_bp',__name__,url_prefix='/pay')
api = Api(pay_bp)

# @api.representation('application/json')
# def output_json(data, code, headers=None):
#     resp = custom_json(data, code, headers=None)
#     return resp

class OrderCreate(Resource):
    @login_auth
    def get(self):
        order = str(datetime.datetime.now().strftime('%Y%m%d%H%M%S')) + str(g.uid) + str(random.randint(10000,99999))
        return jsonify({'order':order,'code':200})

class AlipayAPI(Resource):
    def __init__(self):
        self.app_private_key_string = open('syl_project/pay/app_private_key.txt').read()
        self.alipay_public_key_string = open('syl_project/pay/alipay_public_key.txt').read()

    # def get_alipay_obj(self):
        self.alipay = AliPay(
            appid="2021000119635001",  # 沙箱appid
            app_notify_url='http://127.0.0.1:8080/callback',  # 默认回调url
            # app_private_key_string=self.app_private_key_string,
            # # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
            # alipay_public_key_string=self.alipay_public_key_string,
            app_private_key_string=self.app_private_key_string,
            # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
            alipay_public_key_string=self.alipay_public_key_string,
            sign_type="RSA2",  # RSA 或者 RSA2
            debug=True,  # 默认False,我们是沙箱，所以改成True(让访问沙箱环境支付宝地址)
        )
        # return alipay
    @login_auth
    def get(self):

        parser = reqparse.RequestParser()
        parser.add_argument('order')
        parser.add_argument('price')
        parser.add_argument('record')
        args = parser.parse_args()
        order = args['order']
        price = args['price']
        record = args['record']
        user_id = g.uid
        # with transaction.atomic():
        #     # 创建事物回滚点
        #     point = transaction.savepoint()
        if record == '普通会员':
            record = 1
        else:
            record = 2
        try:
            order = Orders(user=user_id, vip=record, total_amount=price, order_id=order,
                           pay_time=datetime.datetime.now())
            db.session.add(order)
            db.session.commit()
            # transaction.savepoint_commit(point)  # 事务提交

        except Exception as e:
            # transaction.savepoint_rollback(point)  # 事务回滚
            logging.error(e)  # 将报错写入日志
            print('订单错误',e)
            return jsonify(code=400, msg='订单创建失败')

        order_str = self.alipay.api_alipay_trade_page_pay(
            out_trade_no="%s"%order,  # 订单id，应该从前端获取
            total_amount=price,  # 订单总金额
            subject="测试阿里云付款",  # 付款标题信息
        )
        alipay_url = 'https://openapi.alipaydev.com/gateway.do?'+order_str
        return jsonify(code=200,msg='订单创建成功，正在跳转支付界面',url=alipay_url)

    # @login_auth
    # def post(self):
    #     '''创建订单'''
    #     user_id = g.uid
    #     parser = reqparse.RequestParser()
    #     parser.add_argument('order')
    #     parser.add_argument('price')
    #     parser.add_argument('record')
    #     args = parser.parse_args()
    #     order = args['order']
    #     price = args['price']
    #     record = args['record']
    #     with transaction.atomic():
    #         # 创建事物回滚点
    #         point = transaction.savepoint()
    #         try:
    #             order = Orders(user=user_id,vip=record,total_amount=price,order_id=order,pay_time=datetime.datetime.now())
    #             db.session.add(order)
    #             db.session.commit()
    #             transaction.savepoint_commit(point)  # 事务提交
    #             return jsonify(code=200, msg='订单创建成功')
    #         except Exception as e:
    #             transaction.savepoint_rollback(point)  # 事务回滚
    #             logging.error(e)  # 将报错写入日志
    #             return jsonify(code=400,msg='订单创建失败')



class Alipaycallback(Resource):
    @login_auth
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('trade_no')
        parser.add_argument('order_id')
        parser.add_argument('timestamp')
        parser.add_argument('pay_amount')
        args = parser.parse_args()
        trade_no = args['trade_no']
        order_id = args['order_id']
        pay_amount = args['pay_amount']
        uid = g.uid
        order = Orders.query.filter_by(order_id=order_id).first()
        if not order:
            return jsonify(code=400,msg='购买失败')
        else:
            order.trade_no = trade_no
            order.status = 1
            db.session.commit()
            return jsonify(code=200, msg='购买成功')


api.add_resource(OrderCreate,'/create_order')
api.add_resource(AlipayAPI,'/alipay')
api.add_resource(Alipaycallback,'/callback')
